import { App, Button, Checkbox, Divider, Flex, Modal } from 'antd';
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import { createStyles } from 'antd-style';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useCatch } from '@/hooks';
import RoleServices from '@/api/services/roleServices.ts';
import { useRoleList, useUserId } from '@/store/userStore.ts';
import { useEffect, useMemo, useRef, useState } from 'react';
import EditRoleModal, { EditRoleModalRef } from './components/EditRoleModal';
import IconEdit from './components/IconEdit';
import IconDelete from './components/IconDelete';
import PermissionGuard from '@/components/PermissionGuard';

const useStyle = createStyles(({ css }) => {
  return {
    item: css`
      padding: 13px 32px;

      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      line-height: 22px; /* 157.143% */
      border-radius: 8px;
      color: var(--ycx-font-color-l2);
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &:hover {
        background: #d5e0ff;
      }

      &.active {
        background: var(--ycx-primary-color);
        color: var(--ycx-font-color);
      }
    `,
    iconWrapper: css`
      display: flex;
      gap: 8px;
    `,
  };
});

const RoleManagement = () => {
  const { message } = App.useApp();
  const { styles } = useStyle();
  const catchFn = useCatch();
  const id = useUserId();
  const [activeKey, setActiveKey] = useState(0);
  const roleList = useRoleList();
  const editRoleModalRef = useRef<EditRoleModalRef>(null);
  const { confirm } = Modal;

  const { data: roleOptions, refetch: refetchRoleOptions } = useQuery({
    queryKey: ['role-list', id],
    queryFn: () => catchFn(() => RoleServices.getRolesByUserId({ userId: id! })),
    select: ({ data }) => data.map((i) => ({ label: i.roleName, value: i.id })),
  });

  const { data: roleDetail, refetch: refetchRoleDetail } = useQuery({
    queryKey: ['role-list', activeKey],
    queryFn: () => catchFn(() => RoleServices.getRoleDetail(activeKey)),
    select: ({ data }) => data,
    enabled: !!activeKey,
    staleTime: 0,
  });

  const { data: menu } = useQuery({
    queryKey: ['all-menu'],
    queryFn: () => catchFn(() => RoleServices.getMenuList()),
    select: ({ data }) => data,
    enabled: id === 1,
    staleTime: 0,
  });

  const { mutate: deleteRole } = useMutation({
    mutationFn: RoleServices.deleteRole,
    onSuccess: () => {
      message.success('删除成功');
      refetchRoleOptions();
    },
    onError: (error) => message.error(error.message),
  });

  const showConfirm = (roleName: string, roleId: number) => {
    confirm({
      title: '删除角色',
      icon: <ExclamationCircleFilled />,
      content: `确认删除角色【${roleName}】吗？`,
      onOk() {
        deleteRole(roleId);
      },
    });
  };

  useEffect(() => {
    if (!roleOptions) return;
    setActiveKey(roleOptions[0]?.value);
  }, [roleOptions]);

  const allPermissions = useMemo(() => {
    return menu ?? roleList[0].menuVoList;
  }, [menu, roleList]);

  return (
    <>
      <Flex className="h-full" gap={40}>
        <Flex vertical gap={40} className="h-full w-1/5 min-w-64">
          <Flex justify="space-between">
            <span className="break-keep text-base">角色组</span>
            <PermissionGuard permissions={['ROLE_SAVE', 'ROLE_ASSIGN_MENU']}>
              <Button
                type="primary"
                ghost
                size="small"
                icon={<PlusOutlined />}
                onClick={() => editRoleModalRef.current?.open()}
              >
                添加角色
              </Button>
            </PermissionGuard>
          </Flex>

          <Flex vertical gap={16}>
            {roleOptions?.map((i) => (
              <div
                key={i.value}
                className={`${styles.item} ${activeKey === i.value ? 'active' : ''}`}
                onClick={() => setActiveKey(i.value)}
              >
                <span className="break-keep">{i.label}</span>
                <div className={styles.iconWrapper}>
                  <PermissionGuard permissions={['ROLE_UPDATE', 'ROLE_ASSIGN_MENU']}>
                    <span
                      onClick={() => {
                        editRoleModalRef.current?.open(i.value);
                      }}
                    >
                      <IconEdit color={activeKey === i.value ? '#fff' : undefined} />
                    </span>
                  </PermissionGuard>
                  <PermissionGuard permissions={['ROLE_UPDATE']}>
                    <span
                      onClick={() => {
                        showConfirm(i.label, i.value);
                      }}
                    >
                      <IconDelete color={activeKey === i.value ? '#fff' : undefined} />
                    </span>
                  </PermissionGuard>
                </div>
              </div>
            ))}
          </Flex>
        </Flex>
        <Divider type="vertical" className="h-full"></Divider>
        <Flex className="h-full flex-1" vertical>
          <div className="mb-10 text-base">权限列表</div>
          <Flex vertical gap={12} className="overflow-y-scroll pr-6">
            {allPermissions.map((item) => (
              <div
                key={item.id}
                className="rounded-lg px-4 py-6"
                style={{ background: 'var(--ycx-card-bg-color)' }}
              >
                <div>
                  <Checkbox checked={!!roleDetail?.menuVoList?.find((i) => i.id === item.id)}>
                    {item.menuName}
                  </Checkbox>
                </div>
                {item.childrenMenu && item.childrenMenu.length > 0 && (
                  <>
                    <Divider style={{ margin: '12px 0 16px' }} />
                    <div>
                      {item.childrenMenu?.map((child) => {
                        return child.childrenMenu && child.childrenMenu.length > 0 ? (
                          <div key={child.id} className="pb-4">
                            <Checkbox
                              key={child.id}
                              className="w-1/5 break-keep"
                              checked={!!roleDetail?.menuVoList?.find((i) => i.id === child.id)}
                            >
                              {child.menuName}
                            </Checkbox>
                            {/*<Divider type='vertical'/>*/}
                            {child.childrenMenu.map((sub) => (
                              <Checkbox
                                key={sub.id}
                                className="w-1/5 break-keep"
                                checked={!!roleDetail?.menuVoList?.find((i) => i.id === sub.id)}
                              >
                                {sub.menuName}
                              </Checkbox>
                            ))}
                          </div>
                        ) : (
                          <Checkbox
                            key={child.id}
                            className="w-1/5 break-keep"
                            checked={!!roleDetail?.menuVoList?.find((i) => i.id === child.id)}
                          >
                            {child.menuName}
                          </Checkbox>
                        );
                      })}
                    </div>
                  </>
                )}
              </div>
            ))}
          </Flex>
        </Flex>
      </Flex>
      <EditRoleModal
        ref={editRoleModalRef}
        allPermissions={allPermissions}
        onSuccess={() => {
          refetchRoleOptions();
          refetchRoleDetail();
        }}
      />
    </>
  );
};

export default RoleManagement;
